#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QTcpServer>
#include <QTcpSocket>
#include <QThread>
#include <QMutex>
#include <QQueue>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QTimer>
#include <QDir>
#include <QStandardPaths>

// 简化的消息类型
enum MessageType {
    SQL_QUERY = 0,
    IMAGE_UPLOAD = 1,
    IMAGE_DOWNLOAD = 2
};

class DatabaseAccess : public QObject {
    Q_OBJECT
public:
    DatabaseAccess(QObject *parent = nullptr);
    bool executeQuery(const QString &queryStr);
    QSqlQuery runQuery(const QString &queryStr);
    QString saveImageMessage(int patientId, int doctorId, const QString &direction, 
                            const QByteArray &imageData, const QString &fileName);

private:
    QSqlDatabase m_db;
    QString m_imageStoragePath;
    void initializeImageStorage();
};

class Server;

class ClientConnection : public QObject {
    Q_OBJECT
public:
    ClientConnection(QTcpSocket *socket, Server *server, QObject *parent = nullptr);

private slots:
    void slotReadyRead();
    void slotDisconnected();

signals:
    void disconnected();

private:
    void handleSqlQuery(const QString &query);
    void handleJsonMessage(const QByteArray &jsonData);  // 添加这行
    void handleImageUpload(const QByteArray &messageData);  // 修正参数
    void handleImageDownload(const QString &fileName);
    
    QTcpSocket *clientSocket;
    Server *m_server;
    QByteArray m_buffer;
    qint64 m_expectedSize;
    MessageType m_currentMessageType;
    bool m_headerReceived;
};

class Server : public QObject {
    Q_OBJECT
public:
    Server(quint16 port, QObject *parent = nullptr);

private slots:
    void onNewConnection();
    void processQueries();

public slots:
    void addQueryToQueue(const QString &query, QTcpSocket *clientSocket);

private:
    QTcpServer *tcpServer;
    QQueue<QPair<QString, QTcpSocket*>> queryQueue;
    DatabaseAccess *dbAccess;  // 调整初始化顺序
    QMutex *mutex;
};

#endif // TCPSERVER_H
